<template>
  <div>
    <p class="title">新增码表</p>
    <a-form :model="stopwatch" v-bind="layout" name="nest-messages" :rules="rules">
      <a-form-item name="name" label="码表名称">
        <a-input v-model:value="stopwatch.name" placeholder="请输入标准的中文名称" :maxlength="30" />
      </a-form-item>
      <a-form-item name="introduction" label="码表说明">
        <a-textarea v-model:value="stopwatch.illustrate" show-count :maxlength="200" />
      </a-form-item>
      <a-form-item name="configuration" label="编码配置">
        <a-button type="primary" style="margin-left: 80%" size="small" @click="handleAdd">添加</a-button>
      </a-form-item>

      <a-table bordered :data-source="stopwatch.detail" :columns="columns" size="small" :scroll="{ y: 'calc(100vh - 400px)' }" :pagination="false">
        <template #headerCell="{ column }">
          <template v-if="column.dataIndex === 'encodingValue' || column.dataIndex === 'encodingName'"> <i>*</i>{{ column.title }} </template>
        </template>
        <template #bodyCell="{ column, record, text }">
          <template v-if="['encodingValue', 'encodingName', 'encodingMeaning'].includes(column.dataIndex)">
            <a-input v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]" :maxlength="8" :style="msg.valueClass" placeholder="必填"></a-input>
            <template v-else>
              {{ text }}
            </template>
          </template>
          <!--           <template v-if="column.dataIndex === 'encodingName' && record.showStatus">
            <a-input v-model:value.trim="record.encodingName" :maxlength="8" :style="msg.nameClass" placeholder="必填"> </a-input>
          </template>
          <template v-if="column.dataIndex === 'encodingMeaning' && record.showStatus">
            <a-input v-model:value="record.encodingMeaning" placeholder="请输入码值含义"></a-input>
          </template> -->

          <!-- 删除操作按钮 -->
          <template v-else-if="column.dataIndex === 'operation'">
            <template v-if="editableData[record.id]">
              <a-popconfirm v-if="stopwatch.detail.length" title="是否保存更改?" @confirm="save(record)">
                <a>保存 </a>
              </a-popconfirm>
              <a-popconfirm v-if="stopwatch.detail.length" title="是否取消更改?" @confirm="cancel(record)">
                <a> 取消</a>
              </a-popconfirm>
            </template>
            <template v-else>
              <a-popconfirm title="是否对此条配置进行更改?" @confirm="onUpdate(record)">
                <a>编辑 </a>
              </a-popconfirm>
              <a-popconfirm title="是否删除此条配置?" @confirm="onDelete(record)">
                <a> 删除</a>
              </a-popconfirm>
            </template>
          </template>
        </template>
      </a-table>
      <div class="msg_en"
        ><span>{{ msg.encodingValue }}</span
        ><span>{{ msg.encodingName }}</span></div
      >
      <a-form-item :wrapper-col="{ span: 14, offset: 8 }" style="margin-top: 5%">
        <a-button type="primary" html-type="submit" @click="insertStopwatch">确定</a-button>
        <a-button style="margin-left: 20px" @click="cancelDrawer">取消</a-button>
      </a-form-item>
    </a-form>
  </div>
  <!-- <div class="stopwatch_input">
    <div class="stopwatchInfo"
      ><span> <i>*</i> 码表名称：</span
      ><a-input
        v-model:value.trim="stopwatch.name"
        :style="msg.class"
        :maxlength="14"
        :rules="[{ required: true, message: 'Please input your username!' }]"
        placeholder="请输入标准的中文名称"
        @blur="verifyStopwatchName"
    /></div>
    <div class="msg">{{ msg.name }}</div>
    <div class="stopwatchInfo"><span>码表说明：</span> <a-textarea v-model:value="stopwatch.illustrate" placeholder="输入标准说明" :auto-size="{ minRows: 2, maxRows: 3 }" /></div>
  </div>
  <div class="encodingConfiguration">
    <div class="encodingConfiguration_btn">
      <p><i>*</i><span>编码配置：</span></p>
      <a-button type="primary" size="small" :disabled="!isAdd" @click="handleAdd">添加+</a-button>
    </div>
    <div class="encodingConfiguration_bottom">
      <div>
        <a-table bordered :data-source="stopwatch.detail" :columns="columns" size="small" :scroll="{ y: 'calc(100vh - 400px)' }" :pagination="false">
          <template #headerCell="{ column }">
            <template v-if="column.dataIndex === 'encodingValue' || column.dataIndex === 'encodingName'"> <i>*</i>{{ column.title }} </template>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'encodingValue' && record.showStatus">
              <a-input v-model:value.trim="record.encodingValue" :maxlength="8" :style="msg.valueClass" placeholder="必填"></a-input>
            </template>
            <template v-if="column.dataIndex === 'encodingName' && record.showStatus">
              <a-input v-model:value.trim="record.encodingName" :maxlength="8" :style="msg.nameClass" placeholder="必填"> </a-input>
            </template>
            <template v-if="column.dataIndex === 'encodingMeaning' && record.showStatus">
              <a-input v-model:value="record.encodingMeaning" placeholder="请输入码值含义"></a-input>
            </template>

            <template v-else-if="column.dataIndex === 'operation' && record.showStatus === false">
              <a-popconfirm title="是否对此条配置进行更改?" @confirm="onUpdate(record)">
                <a>编辑 </a>
              </a-popconfirm>
              <a-popconfirm title="是否删除此条配置?" @confirm="onDelete(record)">
                <a> 删除</a>
              </a-popconfirm>
            </template>

            <template v-else-if="column.dataIndex === 'operation' && record.showStatus === true">
              <a-popconfirm v-if="stopwatch.detail.length" title="是否保存更改?" @confirm="save(record)">
                <a>保存 </a>
              </a-popconfirm>
              <a-popconfirm v-if="stopwatch.detail.length" title="是否取消更改?" @confirm="cancel(record)">
                <a> 取消</a>
              </a-popconfirm>
            </template>
          </template>
        </a-table>
        <div class="msg_en"
          ><span>{{ msg.encodingValue }}</span
          ><span>{{ msg.encodingName }}</span></div
        >
      </div>
      <div class="btn">
        <a-space>
          <a-button @click="cancelDrawer">取消</a-button>
          <a-button type="primary" @click="insertStopwatch">确定</a-button>
        </a-space>
      </div>
    </div>
  </div> -->
</template>

<script lang="ts" setup>
  import type { UnwrapRef } from 'vue';
  import { addStopwatch, updateStopwatch } from '@/api/test/index';
  import { insertStopwatchType, stopwatchConfig } from '../specification';
  import { message } from 'ant-design-vue';
  import { getDetailHooks } from '@/hooks/CodeTablesHooks/getStopwatchDetailHooks';
  import { getListHooks } from '@/hooks/CodeTablesHooks/getstopwatchDataHooks';
  import { cloneDeep } from 'lodash-es';
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };
  const rules = {
    name: [
      {
        required: true,
        message: '码表名称不能为空',
      },
      {
        pattern: /^[A-Za-z\u4E00-\u9FA5]*$/,
        message: '码表名称只能由中文或英文组合',
        validateTrigger: 'onBlur',
      },
    ],
  };
  // 表头
  const columns = [
    {
      title: '码值取值',
      dataIndex: 'encodingValue',
      align: 'center',
      width: '20%',
    },
    {
      title: '码值名称',
      dataIndex: 'encodingName',
      align: 'center',
      width: '20%',
    },
    {
      title: '码值含义',
      dataIndex: 'encodingMeaning',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '20%',
      align: 'center',
    },
  ];
  // 用户输入错误的提示文字
  const msg = ref<{ [key: string]: any }>({});
  // 调用查询
  const { getData, table } = getListHooks();
  // 获取到码表信息
  const { stopwatch, drawer, cuStatus } = getDetailHooks();
  // 暂存编码配置数据---用于还原用户点击编辑后点击取消
  const editableData: UnwrapRef<Record<string, stopwatchConfig>> = reactive({});
  // 暂存编码配置数据---用于判断是否有相同的码值取值和码值名称
  const judgeList = ref<stopwatchConfig[]>([]);
  /*   // 暂存的码表名字
  const StagName = ref<String>();
  StagName.value = stopwatch.name; */
  // 中文和英文的正则
  const regular = /^[A-Za-z\u4E00-\u9FA5]*$/;
  // 校验用户输入的码表名称是否为空
  const verifyStopwatchName = () => {
    if (stopwatch.name == '') {
      msg.value.name = '码表名称不能为空';
      msg.value.class = 'border: 2px solid red;';
      return false;
    } else {
      console.log(`正则: ${regular.test(stopwatch.name)}`);
      if (regular.test(stopwatch.name)) {
        msg.value.name = '';
        msg.value.class = '';
        return true;
      } else {
        msg.value.name = '码表名称只能由中文或英文组合';
        msg.value.class = 'border: 2px solid red;';
        return false;
      }
    }
  };
  /* 校验用户的码表配置信息
   * verifyEncodingValue ---校验码值取值
   * verifyEncodingName ---校验码值名称
   */
  const verifyEncodingValue = (encodingValue: string) => {
    if (encodingValue == '') {
      msg.value.encodingValue = '码值取值不能为空';
      msg.value.valueClass = 'border: 1px solid red;';
      return false;
    } else {
      let bool = ref<boolean>(true);
      judgeList.value.forEach((item: { [arg: string]: any }) => {
        if (encodingValue == item.encodingValue) {
          msg.value.encodingValue = '码值取值不能重复';
          msg.value.valueClass = 'border: 1px solid red;';
          bool.value = false;
        }
      });

      console.log(bool.value);
      if (bool.value) {
        msg.value.encodingValue = '';
        msg.value.valueClass = '';
      }
      return bool.value;
    }
  };
  const verifyEncodingName = (encodingName: string) => {
    console.log(`需要验证的信息： ${encodingName}`);

    if (encodingName == '') {
      msg.value.encodingName = '码值名称不能为空';
      msg.value.nameClass = 'border: 1px solid red;';
      return false;
    } else {
      console.log(`需要验证的信息： ${encodingName}--${judgeList.value.length}`);
      let bool = ref<boolean>(true);
      judgeList.value.forEach((item: { [arg: string]: any }) => {
        console.log(`${encodingName == item.encodingName}---${item.encodingName}`);

        if (encodingName == item.encodingName) {
          msg.value.encodingName = '码值名称不能重复';
          msg.value.nameClass = 'border: 1px solid red;';
          bool.value = false;
        }
      });
      if (!regular.test(encodingName)) {
        msg.value.encodingName = '码值取值只能由中文或英文组合';
        msg.value.nameClass = 'border: 1px solid red;';
        bool.value = false;
      }
      console.log(bool.value);
      if (bool.value) {
        msg.value.encodingName = '';
        msg.value.nameClass = '';
      }
      return bool.value;
    }
  };
  // 编辑码表配置
  const onUpdate = (record: stopwatchConfig) => {
    // editableData[record.id] = record;
    editableData[record.id] = cloneDeep(stopwatch.detail.filter(item => record.id === item.id)[0]);
  };
  // 删除码表配置
  const onDelete = (e: stopwatchConfig) => {
    console.log('删除： ', JSON.stringify(e));
    stopwatch.detail = stopwatch.detail.filter(item => item.id !== e.id);
  };
  // 保存码表配置
  const save = (record: stopwatchConfig) => {
    const nameFlag: boolean = verifyEncodingName(e.encodingName);
    const valueFlag: boolean = verifyEncodingValue(e.encodingValue);
    if (nameFlag && valueFlag) {
      Object.assign(record, editableData[record.id]);
      delete editableData[record.id];
    }
  };
  // 取消码表配置
  const cancel = (record: stopwatchConfig) => {
    if (record.encodingValue == '' || record.encodingName == '') {
      stopwatch.detail = stopwatch.detail.filter(item => item.id !== record.id);
    }
    delete editableData[record.id];
  };
  // 添加码表配置项
  const handleAdd = () => {
    const newData: stopwatchConfig = {
      id: new Date().getTime(),
      encodingValue: '',
      encodingName: '',
      encodingMeaning: '',
    };
    editableData[newData.id] = newData;
    stopwatch.detail.push(newData);
  };
  // 发送请求添加或修改码表
  const insertStopwatch = async () => {
    const dataList: stopwatchConfig[] = JSON.parse(JSON.stringify(stopwatch.detail));
    let flag = verifyStopwatchName();
    if (flag) {
      if (dataList.length > 0) {
        if (encodingList.value.length == 0) {
          //删除能否修改的状态值和id
          // dataList.forEach(item => {
          //   delete item.showStatus;
          //   delete item.id;
          // });
          let data: insertStopwatchType = {
            stopwatchName: stopwatch.name,
            stopwatchIllustrate: stopwatch.illustrate,
            configList: dataList,
          };
          if (cuStatus.value == 0) {
            await addStopwatch(data);
            drawer.value = false;
            table.num = 1;
            table.size = 10;
            getData();
          } else if (cuStatus.value == 1) {
            data.stopwatchCode = stopwatch.code;
            /*   if (stopwatch.name == StagName.value) {
              data.stopwatchName = '';
            } */
            await updateStopwatch(data);
            drawer.value = false;
            table.num = 1;
            table.size = 10;
            getData();
          }
        } else {
          message.destroy();
          message.warning('请先保存在提交');
        }
      } else {
        message.destroy();
        message.warning('编码配置至少有一项');
      }
    }
  };
  // 关闭抽屉
  const cancelDrawer = () => {
    drawer.value = false;
  };
</script>

<style lang="less" scoped>
  i {
    font-size: 20px;
    color: red;
  }

  .msg {
    height: 30px;
    font-size: 16px;
    text-align: center;
    color: red;
  }

  .msg_en {
    display: flex;
    font-size: 10px;
    font-weight: 600;
    color: red;

    span {
      padding: 7px;
      width: 110px;
    }
  }

  .ant-drawer-body {
    padding: 0;

    .stopwatch_input {
      border-bottom: 2px solid #ccc;
      width: 100%;
      height: 150px;

      .stopwatchInfo {
        display: flex;
        justify-content: center;
        align-items: center;

        span {
          width: 100px;
          font-weight: 600;
          text-align: right;
        }

        .ant-input {
          width: 400px;
        }

        .ant-input-textarea {
          width: 400px;
        }
      }
    }

    .encodingConfiguration {
      margin-top: 20px;

      .encodingConfiguration_btn {
        display: flex;
        justify-content: space-between;
        padding: 0 30px;

        span {
          font-weight: 600;
        }
      }
    }
  }

  .encodingConfiguration_bottom {
    display: flex;
    justify-content: space-between;
    height: 470px;
    flex-direction: column;

    .btn {
      .ant-space {
        display: flex;
        justify-content: space-evenly;
      }
    }
  }

  .title {
    font-size: 20px;
    text-align: center;
  }
</style>
